package com.micro.service.impl;

import com.micro.client.TrainServiceClient;
import com.micro.client.UserServiceClient;
import com.micro.dto.TrainOrderDTO;
import com.micro.entity.TrainTicketOrder;
import com.micro.repository.TrainTicketOrderRepository;
import com.micro.request.TicketCreatingRequest;
import com.micro.service.TrainTicketOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Time;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class TrainTicketOrderServiceImpl implements TrainTicketOrderService {

    @Autowired
    private TrainTicketOrderRepository trainTicketOrderRepository;
    
    @Autowired
    private UserServiceClient userServiceClient;
    
    @Autowired
    private TrainServiceClient trainServiceClient;

    @Override
    @Transactional
    public void createOrder(TicketCreatingRequest request) {
        // 1. 获取用户信息
        UserServiceClient.UserDTO user = userServiceClient.getUserByUsername(request.getUserName());
        
        // 2. 获取列车信息
        Map<String, Object> trainMap = trainServiceClient.getTrainByNumber(request.getTrainNumber());
        
        // 调试信息
        System.out.println("DEBUG - 获取到的列车信息:");
        System.out.println("  trainMap: " + trainMap);
        
        if (trainMap == null || trainMap.isEmpty()) {
            throw new RuntimeException("列车信息为空，无法继续处理");
        }
        
        // 从Map中提取数据
        Long trainId = null;
        String trainNumber = null;
        Long departureStationId = null;
        Long terminalStationId = null;
        String departureTime = null;
        String arrivalTime = null;
        
        // 尝试不同的字段名（先检查英文字段名，再检查中文字段名）
        if (trainMap.containsKey("trainId") && trainMap.get("trainId") != null) {
            trainId = Long.valueOf(trainMap.get("trainId").toString());
        } else if (trainMap.containsKey("列车ID") && trainMap.get("列车ID") != null) {
            trainId = Long.valueOf(trainMap.get("列车ID").toString());
        }
        
        if (trainMap.containsKey("trainNumber") && trainMap.get("trainNumber") != null) {
            trainNumber = trainMap.get("trainNumber").toString();
        } else if (trainMap.containsKey("车次") && trainMap.get("车次") != null) {
            trainNumber = trainMap.get("车次").toString();
        }
        
        if (trainMap.containsKey("departureStationId") && trainMap.get("departureStationId") != null) {
            departureStationId = Long.valueOf(trainMap.get("departureStationId").toString());
        } else if (trainMap.containsKey("始发站ID") && trainMap.get("始发站ID") != null) {
            departureStationId = Long.valueOf(trainMap.get("始发站ID").toString());
        }
        
        if (trainMap.containsKey("terminalStationId") && trainMap.get("terminalStationId") != null) {
            terminalStationId = Long.valueOf(trainMap.get("terminalStationId").toString());
        } else if (trainMap.containsKey("终点站ID") && trainMap.get("终点站ID") != null) {
            terminalStationId = Long.valueOf(trainMap.get("终点站ID").toString());
        }
        
        if (trainMap.containsKey("departureTime") && trainMap.get("departureTime") != null) {
            departureTime = trainMap.get("departureTime").toString();
        } else if (trainMap.containsKey("始发时间") && trainMap.get("始发时间") != null) {
            departureTime = trainMap.get("始发时间").toString();
        }
        
        if (trainMap.containsKey("arrivalTime") && trainMap.get("arrivalTime") != null) {
            arrivalTime = trainMap.get("arrivalTime").toString();
        } else if (trainMap.containsKey("终到时间") && trainMap.get("终到时间") != null) {
            arrivalTime = trainMap.get("终到时间").toString();
        }
        
        System.out.println("DEBUG - 解析后的列车信息:");
        System.out.println("  trainId: " + trainId);
        System.out.println("  trainNumber: " + trainNumber);
        System.out.println("  departureStationId: " + departureStationId);
        System.out.println("  terminalStationId: " + terminalStationId);
        System.out.println("  departureTime: " + departureTime);
        System.out.println("  arrivalTime: " + arrivalTime);
        
        if (trainId == null) {
            throw new RuntimeException("列车ID为空，无法继续处理");
        }
        
        // 3. 计算日期偏移
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate dataParsed = LocalDate.parse(request.getDate(), formatter);
        long dayOffset = ChronoUnit.DAYS.between(LocalDate.now(), dataParsed);
        
        // 4. 调用购票服务获取座位ID
        Long seatId = trainServiceClient.purchaseTicket(
                trainId,
                convertSeatType(request.getSeatType()),
                1, // 购买1张票
                request.getDate()
        );

        // 5. 获取座位信息以获取车厢ID
        Map<String, Object> seatInfo = trainServiceClient.getSeatById(seatId);
        Long carriageId = null;
        if (seatInfo != null && seatInfo.containsKey("车厢ID")) {
            carriageId = Long.valueOf(seatInfo.get("车厢ID").toString());
        } else if (seatInfo != null && seatInfo.containsKey("carriageId")) {
            carriageId = Long.valueOf(seatInfo.get("carriageId").toString());
        } else {
            // 如果无法获取车厢ID，使用默认值1
            carriageId = 1L;
        }

        // 6. 根据身份证号获取乘客信息
        UserServiceClient.PassengerDTO passenger = userServiceClient.getPassengerByIdCard(request.getIdCard());
        Long passengerId = null;
        if (passenger != null && passenger.getPassengerId() != null) {
            passengerId = passenger.getPassengerId();
        } else {
            // 如果无法获取乘客ID，使用用户ID作为乘客ID
            passengerId = user.getUserId();
        }

        // 7. 创建订单实体
        TrainTicketOrder order = new TrainTicketOrder();
        order.setTrainId(trainId);
        order.setUserId(user.getUserId()); // 设置购买者ID
        order.setDepartureStationId(departureStationId);
        order.setArrivalStationId(terminalStationId);
        order.setCarriageId(carriageId); // 设置车厢ID
        order.setSeatId(seatId);
        order.setSeatType(request.getSeatType());
        order.setPassengerId(passengerId); // 设置乘客ID
        order.setPassengerName(request.getName());
        order.setPassengerIdCard(request.getIdCard());
        order.setPrice(request.getPrice());
        order.setTicketStatus((byte) 0); // 已支付
        order.setPaymentTime(LocalDateTime.now());
        order.setTrainData(LocalDate.parse(request.getDate()));
        
        // 设置列车时间信息
        order.setDepartureTime(Time.valueOf(departureTime));
        order.setArrivalTime(Time.valueOf(arrivalTime));
        
        // 8. 保存订单
        trainTicketOrderRepository.insert(order);
    }

    @Override
    public List<TrainTicketOrder> getOrdersByUsername(String username) {
        try {
            UserServiceClient.UserDTO user = userServiceClient.getUserByUsername(username);
            if (user == null || user.getUserId() == null) {
                return new ArrayList<>();
            }
            return trainTicketOrderRepository.findByUserIdOrderByOrderIdDesc(user.getUserId());
        } catch (Exception e) {
            // 如果用户服务不可用或用户不存在，返回空列表
            return new ArrayList<>();
        }
    }

    @Override
    public List<TrainOrderDTO> getOrderDTOsByUsername(String username) {
        List<TrainTicketOrder> orders = getOrdersByUsername(username);
        return orders.stream().map(order -> convertToDTO(order, username)).collect(Collectors.toList());
    }

    @Override
    public TrainTicketOrder getOrderById(Long orderId) {
        return trainTicketOrderRepository.selectById(orderId);
    }

    @Override
    @Transactional
    public boolean refundOrder(Long orderId) {
        TrainTicketOrder order = getOrderById(orderId);
        if (order != null && order.getTicketStatus() == 0) {
            order.setTicketStatus((byte) 1); // 已退票
            trainTicketOrderRepository.updateById(order);
            return true;
        }
        return false;
    }

    @Override
    public List<TrainTicketOrder> getOrdersByUserId(Long userId) {
        return trainTicketOrderRepository.findByUserId(userId);
    }

    @Override
    public List<TrainTicketOrder> getOrdersByTicketStatus(Byte ticketStatus) {
        return trainTicketOrderRepository.findByTicketStatus(ticketStatus);
    }

    @Override
    public List<TrainTicketOrder> getOrdersByTrainId(Long trainId) {
        return trainTicketOrderRepository.findByTrainId(trainId);
    }

    // 转换座位类型
    private Integer convertSeatType(String seatType) {
        switch (seatType) {
            case "一等座": return 1;
            case "二等座": return 2;
            case "商务座": return 3;
            case "硬座": return 4;
            case "硬卧": return 5;
            case "软卧": return 6;
            default: return 2; // 默认二等座
        }
    }

    // 转换为DTO
    private TrainOrderDTO convertToDTO(TrainTicketOrder order, String username) {
        TrainOrderDTO dto = new TrainOrderDTO();
        
        // 调试：打印实体类的所有字段值
        System.out.println("DEBUG - 实体类字段值:");
        System.out.println("  orderId: " + order.getOrderId());
        System.out.println("  userId: " + order.getUserId());
        System.out.println("  trainId: " + order.getTrainId());
        System.out.println("  departureStationId: " + order.getDepartureStationId());
        System.out.println("  arrivalStationId: " + order.getArrivalStationId());
        System.out.println("  seatId: " + order.getSeatId());
        System.out.println("  carriageId: " + order.getCarriageId());
        System.out.println("  seatType: " + order.getSeatType());
        System.out.println("  passengerId: " + order.getPassengerId());
        System.out.println("  passengerName: " + order.getPassengerName());
        System.out.println("  passengerIdCard: " + order.getPassengerIdCard());
        System.out.println("  price: " + order.getPrice());
        System.out.println("  ticketStatus: " + order.getTicketStatus());
        System.out.println("  trainData: " + order.getTrainData());
        System.out.println("  paymentTime: " + order.getPaymentTime());
        System.out.println("  departureTime: " + order.getDepartureTime());
        System.out.println("  arrivalTime: " + order.getArrivalTime());
        
        // 设置基本字段，确保不为null
        dto.setOrderId(order.getOrderId() != null ? order.getOrderId() : 0L);
        dto.setUserId(order.getUserId() != null ? order.getUserId() : 0L);
        dto.setUserName(username != null ? username : "未知用户");
        dto.setTrainId(order.getTrainId() != null ? order.getTrainId() : 0L);
        dto.setSeatType(order.getSeatType() != null ? order.getSeatType() : "未知座位类型");
        dto.setPassengerName(order.getPassengerName() != null ? order.getPassengerName() : "未知乘客");
        dto.setPassengerIdCard(order.getPassengerIdCard() != null ? order.getPassengerIdCard() : "未知身份证");
        dto.setPrice(order.getPrice() != null ? order.getPrice() : java.math.BigDecimal.ZERO);
        dto.setTicketStatus(order.getTicketStatus() != null ? order.getTicketStatus() : (byte) 0);
        dto.setTrainData(order.getTrainData() != null ? order.getTrainData().toString() : "未知日期");
        dto.setPaymentTime(order.getPaymentTime() != null ? order.getPaymentTime().toString() : "未知时间");
        dto.setDepartureTime(order.getDepartureTime() != null ? order.getDepartureTime().toString() : "未知时间");
        dto.setArrivalTime(order.getArrivalTime() != null ? order.getArrivalTime().toString() : "未知时间");
        
        // 设置默认值
        dto.setTrainNumber("未知车次");
        dto.setDepartureStationName("未知站点");
        dto.setArriveStationName("未知站点");
        dto.setCarriageNumber("未知车厢");
        dto.setSeatNumber("未知座位");
        
        // 获取列车和站点信息
        if (order.getTrainId() != null) {
            try {
                System.out.println("DEBUG - 调用 getTrainById，trainId: " + order.getTrainId());
                Map<String, Object> trainMap = trainServiceClient.getTrainById(order.getTrainId());
                System.out.println("DEBUG - getTrainById 成功返回: " + trainMap);
                if (trainMap != null) {
                    dto.setTrainNumber(trainMap.get("车次") != null ? trainMap.get("车次").toString() : 
                                      trainMap.get("trainNumber") != null ? trainMap.get("trainNumber").toString() : "未知车次");
                }
            } catch (Exception e) {
                System.err.println("获取列车信息失败: " + e.getMessage());
                e.printStackTrace();
            }
        } else {
            System.out.println("DEBUG - trainId 为 null，跳过 getTrainById 调用");
        }
        
        if (order.getDepartureStationId() != null) {
            try {
                System.out.println("DEBUG - 调用 getStationById，departureStationId: " + order.getDepartureStationId());
                Map<String, Object> departureStationMap = trainServiceClient.getStationById(order.getDepartureStationId());
                System.out.println("DEBUG - getStationById (departure) 成功返回: " + departureStationMap);
                if (departureStationMap != null) {
                    dto.setDepartureStationName(departureStationMap.get("站点名称") != null ? departureStationMap.get("站点名称").toString() : 
                                               departureStationMap.get("stationName") != null ? departureStationMap.get("stationName").toString() : "未知站点");
                }
            } catch (Exception e) {
                System.err.println("获取出发站信息失败: " + e.getMessage());
                e.printStackTrace();
            }
        } else {
            System.out.println("DEBUG - departureStationId 为 null，跳过 getStationById 调用");
        }
        
        if (order.getArrivalStationId() != null) {
            try {
                System.out.println("DEBUG - 调用 getStationById，arrivalStationId: " + order.getArrivalStationId());
                Map<String, Object> arrivalStationMap = trainServiceClient.getStationById(order.getArrivalStationId());
                System.out.println("DEBUG - getStationById (arrival) 成功返回: " + arrivalStationMap);
                if (arrivalStationMap != null) {
                    dto.setArriveStationName(arrivalStationMap.get("站点名称") != null ? arrivalStationMap.get("站点名称").toString() : 
                                             arrivalStationMap.get("stationName") != null ? arrivalStationMap.get("stationName").toString() : "未知站点");
                }
            } catch (Exception e) {
                System.err.println("获取到达站信息失败: " + e.getMessage());
                e.printStackTrace();
            }
        } else {
            System.out.println("DEBUG - arrivalStationId 为 null，跳过 getStationById 调用");
        }
        
        if (order.getSeatId() != null) {
            try {
                System.out.println("DEBUG - 调用 getSeatById，seatId: " + order.getSeatId());
                Map<String, Object> seatInfo = trainServiceClient.getSeatById(order.getSeatId());
                System.out.println("DEBUG - getSeatById 成功返回: " + seatInfo);
                if (seatInfo != null) {
                    dto.setCarriageNumber(seatInfo.get("车厢号") != null ? seatInfo.get("车厢号").toString() : 
                                         seatInfo.get("carriageNumber") != null ? seatInfo.get("carriageNumber").toString() : 
                                         seatInfo.get("车厢ID") != null ? seatInfo.get("车厢ID").toString() : 
                                         seatInfo.get("carriageId") != null ? seatInfo.get("carriageId").toString() : "未知车厢");
                    dto.setSeatNumber(seatInfo.get("座位号") != null ? seatInfo.get("座位号").toString() : 
                                     seatInfo.get("seatNumber") != null ? seatInfo.get("seatNumber").toString() : "未知座位");
                }
            } catch (Exception e) {
                System.err.println("获取座位信息失败: " + e.getMessage());
                e.printStackTrace();
            }
        } else {
            System.out.println("DEBUG - seatId 为 null，跳过 getSeatById 调用");
        }
        
        return dto;
    }
}
